/*
 * @Author: jack-ZM
 * @Date: 2022-06-20 22:14:40
 * @LastEditors: jack-ZM
 * @LastEditTime: 2022-10-09 14:21:49
 * @FilePath: /vue3ts-admin-template/src/service/index.ts
 * @Description: 封装request整体请求
 *
 * Copyright (c) 2022 by zsm smzhang@fiberhome.com, All Rights Reserved.
 */
import Request from './request';
import type { AxiosRequestConfig, AxiosResponse } from 'axios';
import type { RequestConfig } from './request/types';
import { ElMessage } from 'element-plus';
import { getInfo } from '@/utils/auth';
import router from '@/router';
import whiteList from '@/config/default/whitelist';
import { useLoginInfo } from '@/store/useLoginInfo';

const request = new Request({
    baseURL: process.env.VUE_APP_BASE_URL,
    timeout: 1000 * 60 * 5,
    interceptors: {
        // 实例请求拦截器
        requestInterceptors: (config: AxiosRequestConfig) => {
            if (whiteList.indexOf(config.url as string) !== -1) {
                //在白名单里
                config.headers!['Authorization'] = 'Basic ZmhwdC13YW5neGluOjEyMzQ1Ng==';
            } else {
                const token = getInfo('token');
                config.headers!['Authorization'] = `Bearer ${token}`;
            }
            return config;
        },
        // 实例响应拦截器（status为200时才会走这里）
        responseInterceptors: (res: AxiosResponse) => {
            /**  返回状态值 具体以项目后台为准 
                 返回状态code以及提示message **/
            const { code, message } = res.data || {};
            //异常信息
            let errorMsg = '接口异常';
            //对应特殊需要操作的状态
            switch (code) {
                case -1002:
                    //未登录状态 进入登陆页
                    errorMsg = '未登录状态，将自动进入登陆页';
                    router.push({
                        name: 'login'
                    });
                    break;
                case -1007:
                    //登陆过期 清除token以及一系列操作 进入登陆页
                    errorMsg = '登录状态过期了,将自动进入登陆页';
                    useLoginInfo().resetToken();
                    router.push({
                        name: 'login'
                    });
                    break;
                case 0:
                    break;
            }
            // 异常提示
            if (code && code !== 0) {
                // 示例:  此时为0才是正常
                ElMessage.error(message || errorMsg);
            }
            return res.data;
        }
    }
});

/**
 * @description: 函数的描述
 * @generic D 请求参数
 * @generic T 响应结构
 * @param {RequestConfig} config 不管是GET还是POST请求都使用data
 * @returns {Promise}
 */
const HttpRequest = <T = any>(config: RequestConfig<T>) => {
    return request.request<T>(config);
};
// 取消请求
export const cancelRequest = (url: string | string[]) => {
    return request.cancelRequest(url);
};
// 取消全部请求
export const cancelAllRequest = () => {
    return request.cancelAllRequest();
};
export default HttpRequest;
